using System;
using System.IO;
using System.Text;
using System.Xml;

namespace Pscx.Commands.Internal
{
    public abstract class PscxXmlWriterCommandBase : PscxEncodingCommandBase
    {
        MemoryStream stream;
        TextWriter writer;
        XmlWriter xml;

        protected override void BeginProcessing()
        {
            stream = new MemoryStream();
            writer = new StreamWriter(stream, GetEncoding());
            
            xml = XmlWriter.Create(writer, WriterSettings);
        }

        protected override void EndProcessing()
        {
            xml.Flush();

            byte[] bytes = Utils.RemoveByteOrderMark(stream);
            string text = GetEncoding().GetString(bytes);

            WriteObject(text);
        }

        protected XmlWriter Output
        {
            get { return xml; }
        }

        protected virtual XmlWriterSettings WriterSettings
        {
            get
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.ConformanceLevel = ConformanceLevel.Document;
                settings.Encoding = GetEncoding();
                settings.Indent = true;
            
                return settings;
            }
        }
    }


}
